import React, { useState } from 'react'
import PageFrom from './components/page-form'
import './index.less'
import { Empty, Form, Spin } from 'antd'
import { query } from '../../services/generating-small-program-code'

const formmatPath = (path) => {
  if (!path) {
    return ''
  }
  const tmp = path.split('.html?')
  if (tmp.length !== 2) {
    return ''
  }
  const obj = {}
  tmp[1].split('&').forEach((i) => {
    const [key, value] = i.split('=')
    if (!/^({{[\S]*}})$/.test(value) && value !== '' && value !== ' ') {
      obj[key] = value
    }
  })
  let result = tmp[0]
  Object.keys(obj).forEach((i, k) => {
    if (k === 0) {
      result = `${result}?${i}=${obj[i]}`
    } else {
      result = `${result}&${i}=${obj[i]}`
    }

  })
  return result
}

const useCodeImage = () => {
  const [path, setPath] = useState('')
  const [codePath, setCodePath] = useState('')
  const [codeImagePath, setCodeImagePath] = useState('')
  const [queryLoading, setqueryLoading] = useState(false)

  const queryCodeImage = async ({ path }) => {
    setqueryLoading(true)
    const codePath = formmatPath(path)

    if (!codePath) return

    console.log(codePath)

    let codeImagePath = `http://operation-gateway-fat-alhz.inzm.com/api/operation-wechat-service/services/wxApiQrcodeService/createwxaqrcodeV2?appId=wxb424c7b51691d720&`

    codeImagePath += `path=${encodeURIComponent(codePath)}`
    const data = await query()
    setqueryLoading(false)

    if (data.data) {
      setPath(path)
      setCodePath(codePath)
      setCodeImagePath(codeImagePath)
    }
  }

  return {
    path,
    codePath,
    codeImagePath,
    queryLoading,
    queryCodeImage
  }
}

const CodeInfo = (props) => {
  if (props.loading) {
    return (
      <div style={{ textAlign: 'center', paddingTop: '30px' }}>
        <Spin />
      </div>
    )
  }
  if (!props.path) {
    return <Empty />
  }

  return (
    <div>
      <Form.Item label="二维码原始路径">{props.path}</Form.Item>
      <Form.Item label="二维码真实路径">{props.codePath}</Form.Item>
      <Form.Item label="小程序二维码">
        <img src={props.codeImagePath} alt=""></img>
      </Form.Item>
    </div>
  )
}

const Page = () => {
  const { path, codePath, codeImagePath, queryLoading, queryCodeImage } = useCodeImage()

  const pageFormProps = {
    handleOk(data) {
      queryCodeImage({ path: data.path })
    }
  }

  const codeInfoProps = {
    path: path,
    codePath: codePath,
    codeImagePath: codeImagePath,
    loading: queryLoading
  }

  return (
    <div className="generating-small-program-code">
      <PageFrom {...pageFormProps} />
      <CodeInfo {...codeInfoProps} />
    </div>
  )
}

export default Page
